package com.foreknow.service.impl;

import com.foreknow.bean.Admin;
import com.foreknow.dao.AdminDao;
import com.foreknow.dao.impl.AdminDaoImpl;
import com.foreknow.db.DBManager;
import com.foreknow.service.AdminService;

import java.sql.Connection;
import java.sql.SQLException;

public class AdminServiceImpl implements AdminService {

    @Override
    public Admin isValidate(String username, String password) {
        //连接数据库
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        //调用Dao层的方法
        AdminDaoImpl adminDao = new AdminDaoImpl();
        //注入数据库的连接,调用的是BaseDao中的setConnection方法
        adminDao.setConnection(conn);
        Admin admin = adminDao.login(username,password);
        //处理事务
        return admin;
    }

    @Override
    public boolean save(Admin admin) {
        //连接数据库
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        //调用Dao层的方法
        AdminDaoImpl adminDao = new AdminDaoImpl();
        //注入数据库的连接,调用的是BaseDao中的setConnection方法
        adminDao.setConnection(conn);
        boolean isRight = false;
        try {
            //如果上面的注册方法没有问题手动提交事务
            isRight = adminDao.register(admin);
            conn.commit();
        } catch (SQLException e) {
            //如果上面的注册方法有问题回滚事务
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
        return isRight;
    }

    public static void main(String[] args) {
        AdminService service = new AdminServiceImpl();
//        Admin admin = service.isValidate("fender","123");
//        System.out.println(admin.getUsername() + "--" + admin.getPassword());
        Admin admin = new Admin();
        admin.setUsername("yamaha123");
        admin.setPassword("123");
        boolean isRight = service.save(admin);
        System.out.println(isRight);
    }
}
